var app = getApp();
const Zan = require('../../dist/index');

Page(Object.assign({}, Zan.TopTips, {

	data: {
		order: {},
		isWait: false,
		isTimer: false
	},

	onLoad: function (options) {
		var that = this;
		var id = options.id;

		if (id) {

		} else {
			// get current order
			that.getCurrentOrder();
		}
	},

	onReady: function (e) {

	},

	onShow: function () {
		var that = this;

		// Loop request current order
		var timer = setInterval(() => {
			if (!that.data.isTimer) clearInterval(timer);
			that.getCurrentOrder();
		}, 5000);
	},

	onUnload: function () {
		var that = this;

		that.setData({
			isTimer: false
		});
	},

	onPullDownRefresh: function () {
		var that = this;
		wx.showNavigationBarLoading();
		that.getCurrentOrder(function () {
			wx.hideNavigationBarLoading();
			wx.stopPullDownRefresh();
		});
	},

	getCurrentOrder: function (fn) {
		var that = this;

		app.battery.common('order/current', {ticket: app.data.token}).then(function (r) {
			if (r.code == 0) {
				// 无订单
				that.setData({
					order: {}
				});

				return;
			}
			if (r.cabinetStatus == 0 || r.cabinetStatus == 5) {
				if (that.data.isWait) {
					wx.setNavigationBarColor({
						frontColor: '#ffffff',
						backgroundColor: '#57C98C',
						animation: {
							duration: 0,
							timingFunc: 'easeIn'
						}
					})
				}

				that.setData({
					order: {
						id: r.id,
						leaseHour: r.leaseHour,
						leaseMoney: r.leaseMoney,
						electricity: r.curPower ? r.curPower : 0,
						leaseElectricity: r.consumePower,
						voltage: r.curVoltage,
						cabinetStatus: r.cabinetStatus
					},
					isTimer: true,
					isWait: false
				});
			} else {
				// wait status FFCC33
				wx.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#ffcc33',
					animation: {
						duration: 400,
						timingFunc: 'easeIn'
					}
				});
				that.setData({
					order: {
						id: r.id,
						leaseHour: r.leaseHour,
						leaseMoney: r.leaseMoney,
						electricity: r.curPower ? r.curPower : 0,
						leaseElectricity: r.consumePower,
						voltage: r.curVoltage,
						cabinetStatus: r.cabinetStatus
					},
					isWait: true,
					isTimer: true
				});
			}
			fn && fn();
		}).catch(function (e) {
			that.showZanTopTips(e.message, {type: 'error'});
			fn && fn();
		});
	},

	goToMap: function () {
		wx.navigateTo({ url: "../map/index?id=" + this.data.order.id });
	}
}));